package com.yay.rental.provider;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.Rental;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;


/**
 * Get Started!
 * @author team@getstarted.com.ua
*/
public class RemoteRentalProvider {
	private String TAG = "RemoteRentalProvider";
	
	
	public Rental findById(String rentalId) {
		Map<String, Object> params = new HashMap<String, Object>();
		//params.put("_id", rentalId);
		params.put("query", "normandie");
        params.put("client_id", "123456");
		List<Rental> ret = list(params);
		if(ret != null && ret.size() > 0) {
			return ret.get(0);
		} else {
			return null;
		}
	}
	
	public List<Rental> list(Map<String, Object> params) {
		List<Rental> ret = new ArrayList<Rental>();
		if(params == null) params = new HashMap<String, Object>();
		String data = _search(params);
		if(data != null) {
			try {
		        JSONObject result = new JSONObject(data);
		        JSONArray jArray = result.getJSONArray("results");
				for(int i=0; i < jArray.length(); i++) {
		           ret.add(buildRental(jArray.getJSONObject(i)));
		        }
			} catch(JSONException e) {
	        	Log.e(this.getClass().getName(), e.toString());
			}
		}
		return ret;
	}

	private Rental buildRental(JSONObject jsonObject) throws JSONException {
		Rental rental = new Rental();
		rental.setId(jsonObject.getInt("_id"));
		rental.setName(jsonObject.getString("name"));
		rental.setThumb(jsonObject.getString("thumb"));
		JSONArray pictures = jsonObject.getJSONArray("pictures");
		for(int i=0; i < pictures.length(); i++) {
			rental.getPictures().add(pictures.getString(i));
		}
		rental.setBedrooms(jsonObject.getInt("bedrooms"));
		rental.setBathroom(jsonObject.getInt("bathroom"));
		rental.setRating((float)jsonObject.getDouble("rating"));
		rental.setPrice_min(jsonObject.getString("price_min"));
		rental.setPrice_max(jsonObject.getString("price_max"));
		rental.setCurency(jsonObject.getString("curency"));
		rental.setUnit(jsonObject.getString("unit"));
	    return rental;
	}

		
	// PRIVATE METHODS
	
	private String _search(Map<String, Object> params) {
		String result = "";
		if(params != null && params.size() > 0) {
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			JSONObject json = new JSONObject();
			for(Map.Entry<String, Object> entry : params.entrySet()) {
				try {
					json.put(entry.getKey(), entry.getValue().toString());
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage());
				}
			}
			
			InputStream is = null; 
			// http post
			try {
		        HttpClient httpclient = new DefaultHttpClient();
		        HttpPost httppost = new HttpPost("http://62.75.137.254:8123/search");
		        nameValuePairs.add(new BasicNameValuePair("text", json.toString()));  
	            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        HttpResponse response = httpclient.execute(httppost);
		        HttpEntity entity = response.getEntity();
		        is = entity.getContent();
			} catch(Exception e) {
	        	Log.e(this.getClass().getName(), e.toString());
			}
			
			// convert response to string
			try {
		        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
		        StringBuilder sb = new StringBuilder();
		        String line = null;
		        while((line = reader.readLine()) != null) {
		        	sb.append(line + "\n");
		        }
		        is.close();
		        if(sb.indexOf("\"validity\":\"true\"") >= 0) {
		        	result = sb.toString();
		        }
			} catch(Exception e) {
	        	Log.e(this.getClass().getName(), e.toString());
			}
		}
		return result;
	}
	
}
